package controllers;

import java.util.List;

import models.FriendShip;
import models.User;
import play.Logger;
import play.data.validation.Required;
import play.data.validation.Valid;
import play.data.validation.Validation;
import play.db.jpa.Blob;
import play.libs.Crypto;
import play.libs.Images;
import utils.Constants;
import utils.Secure;

public class Users extends Application {
	
    public static void index() {
        render();
    }
    @Secure(login=false)
	public static void register(){
    	render();
	}
	@Secure(login = false)
	public static void save(@Valid User user){
		if(User.isUsernameExists(user.username)){
			Validation.addError("error", "用户名已存在！");
		}
		if(validation.hasErrors()){
    		validation.keep();
    		login();
    	}
		user.password = Crypto.passwordHash(user.password);
		user.save();
		loginSession(user.id,user.username);
		Stories.list(user.id);
	}
	/**
	 * 转到登陆页面
	 */
	@Secure(login=false)
	public static void login(){
		render();
	}
	/**
	 * 注销用户
	 */
	public static void logout(){
		logoutSession();
		login();
	}
	/**
	 * 用户登陆
	 * @param username
	 * @param password
	 */
	@Secure(login=false)
	public static void doLogin(String username,String password){
		User u = User.find("username = ?", username).first();
		if (u == null || !u.loginWithPassword(password)) {
			Validation.addError("error", "用户名或密码错误！");
			Validation.keep();
			login();
		}
		loginSession(u.id,u.username);
		index();
	}
	public static void list(){
		List<User> users = User.all().fetch();
		render(users);
	}
	/**
	 * 搜索用户
	 * @param value
	 */
	public static void search(String value){
		List<User> users = User.find("name like ?", "%"+ value +"%").fetch();
		render(users);
	}
	/**
	 * 添加到好友/关注
	 * @param friendId
	 */
	public static void addToFriend(@Required Long friendId){
		String result = Constants.AJAX_SUCCESS;
		try{
			FriendShip friendShip = new FriendShip(Long.parseLong(session.get(Constants.USER_ID_IN_SESSION)), friendId);
			friendShip.save();
		}catch(Exception e){
			Logger.error("addToFriend Error", new Object[]{e.getStackTrace()});
			result = Constants.AJAX_FAILED;
		}
		renderJSON(result);
	}
	/**
	 * 删除好友/关注
	 * @param friendShipId
	 */
	public static void removeFriend(@Required Long friendId){
		String result = Constants.AJAX_SUCCESS;
		try{
			Long userId = Long.parseLong(session.get(Constants.USER_ID_IN_SESSION));
			FriendShip friendShip = FriendShip.find("owner.id = ? and friend.id = ?", userId,friendId).first();
			friendShip.delete();
		}catch(Exception e){
			Logger.error("RemoveFriend Error");
			e.printStackTrace();
			result = Constants.AJAX_FAILED;
		}
		renderJSON(result);
	}
	public static void settings(){
		User user = User.findById(Long.parseLong(session.get(Constants.USER_ID_IN_SESSION)));
		render(user);
	}
	/**
	 * 推荐/发现 可能感兴趣的人
	 * TODO
	 */
	public static void recommend(){
		List<User> users = User.findAll();
		render(users);
	}
	/**
	 * 列出关注的人
	 */
	public static void listFollows(){
		List<User> users = User.findAll();
		render(users);
	}
	/**
	 * 上传头像
	 * @param file
	 */
	public static void uploadAvatar(Blob file){
		if(request.isNew){
			Long userId = Long.parseLong(session.get(Constants.USER_ID_IN_SESSION));
			User user = User.findById(userId);
			// Delete old picture
			if (user.avatar.getFile() != null) {
				user.avatar.getFile().delete();
			}
			user.avatar = file;
			user.avatarFileName = file.getFile().getName();
			user.save();
		}
		Users.settings();
	}
	public static void getAvatar(Long userId){
		User user = User.findById(userId);
		response.setContentTypeIfNotSet(user.avatar.type());
		Logger.info(user.avatar.getFile().getName());
		renderBinary(user.avatar.get());
	}
	// ~~~~~~~~~~~~~~~~ private helper ~~~~~~~~~~~~~~~~~~~~~
	
	@Secure(login=false)
	private static void loginSession(Long userId,String username){
		session.put(Constants.USER_ID_IN_SESSION, userId);
		session.put(Constants.USERNAME_IN_SESSION, username);
	}
	private static void logoutSession(){
		session.remove(Constants.USERNAME_IN_SESSION);
		session.remove(Constants.USER_ID_IN_SESSION);
	}
}